package com.example.bigdata.controller;

import com.example.bigdata.mapper.ShopGoodsMapper;
import com.example.bigdata.model.ShopGoods;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author jie
 * @date 2021/4/27 -14:18
 */
@RestController
public class ShopGoodsController {

    @Autowired
    private ShopGoodsMapper shopGoodsMapper;

    private final ConcurrentHashMap<String, Object> cmap = new ConcurrentHashMap<>();
    Logger logger = LoggerFactory.getLogger(this.getClass());


    @GetMapping("/timer")
    public void timer() {
        this.setTimer();
    }

    private void setTimer() {

       final String startFlag = "startFlag";
        if (null != cmap.get(startFlag)) {
            logger.info("=================定时任务已开启============");
            return;
        }

        long forceTime = 24 * 60 * 1000;
        ShopGoods shopGoods = shopGoodsMapper.getOneByOperationTimeDesc();

        if (null == shopGoods) {
            logger.info("============没有需要操作的数据=============");
        }

        if (null != shopGoods) {
            cmap.put(startFlag, '1');
            logger.info("============进入了定时器===================");
            Timer timer = new Timer();
            TimerTask timerTask = new TimerTask() {
                @Override
                public void run() {
                    shopGoodsMapper.updateForTimer(shopGoods.getId());
                    logger.info("=================商品id{}，原底价{}，现底价{}============", shopGoods.getId(), shopGoods.getBaseprice(), shopGoods.getUpdatebaseprice());
                    cmap.remove(startFlag);
                    setTimer();
                }
            };

            long delay = shopGoods.getOperationTime().getTime() + forceTime - System.currentTimeMillis();
            if (delay < 0) {
                delay = 0;
            }
            timer.schedule(timerTask, delay);

        }
    }
}
